package com.jk.controller;

import com.jk.bean.Permission;
import com.jk.bean.Role;
import com.jk.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.QueryParam;
import util.Result;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {
    @Resource
    private RoleService roleService;

    //=====页面
    @RequestMapping("toPower")
    public String toPower(String url, String id, Model mo) {
        mo.addAttribute("msg", id);

        ArrayList<Role> assignRole = new ArrayList<>();

        ArrayList<Role> unassignRole = new ArrayList<>();
        // 先查询出数据库所有的角色
        ArrayList<Role> allRole = roleService.getAllRole();
        // {id:1,name:xxx},{id:2,name:xxx},{id:3,name:xxx},{id:4,name:xxx}

        // 查询当前用户拥有角色id 2,4
        List<Integer> roleIds = roleService.getRoleIdByUserId(id);

        for (Role role : allRole) {

            if (roleIds.contains(role.getId())) {
                  assignRole.add(role);

            } else {
                unassignRole.add(role);
            }
        }
        mo.addAttribute("assignRole", assignRole);// 1
        System.out.println(assignRole.size());

        mo.addAttribute("unassignRole", unassignRole);
        System.out.println(unassignRole.size());
        return url;
    }

    //====根据角色查询权限
    @ResponseBody
    @RequestMapping("queryTreeByRoleid")
    public List<Permission> queryTreeByRoleid(QueryParam pm) {
        List<Permission> list = roleService.queryTreeByRoleid(pm);
        return list;
    }

    //===给用户赋权限
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("addPowerToRole")
    public String addPowerToRole(QueryParam pm) {
        roleService.deletePermissionToRole(pm.getRoleid());
        roleService.addPowerToRole(pm);
        return null;
    }

    //====给用户赋角色
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("addRoleByUserId")
    public String addRoleByUserId(QueryParam pm) {

        roleService.addRoleByUserId(pm);
        return "";
    }

    //=====移除角色
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("removeRoleByUserId")
    public Result removeRoleByUserId(QueryParam pm) {
        Result result = new Result();
        try {
            roleService.romoveRoleByUserId(pm);
            result.setState(true);
            result.setMsg("后台携带的数据");
        } catch (Exception e) {
            result.setState(false);
        } finally {

        }
        return result;
    }

}
